package com.letv.android.client.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.letv.android.young.client.R;
import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.android.client.fragment.AlbumFullControllerFragment;
import com.letv.android.client.fragment.AlbumRoomFullControllerFragment;
import com.letv.core.bean.VideoBean.WatchingFocusItem;
import com.letv.core.utils.BaseTypeUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.util.PageIdConstant;

import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

/**
 * 看点layout
 * 
 * @author zhuqiao
 *
 */
public class WatchingFocusRelativeLayout extends RelativeLayout {
    private Context mContext;
    /**
     * 热区的大小，单位dip
     */
    private final int hotSize = 20;
    /**
     * 在看点上悬停，触发看点的时间阀值，单位dip
     */
    private final int stayTime = 100;
    private View root;
    private LetvSeekBar fullPlayControllerSeekbar;
    /**
     * 方便根据时间查找看点信息
     */
    @SuppressLint("UseSparseArrays")
    private HashMap<Integer, WatchingFocusItem> watchFocuses = new HashMap<Integer, WatchingFocusItem>();

    private TreeSet<Integer> dotTimeTree = new TreeSet<Integer>();

    private ImageView fullPlayControllerPlay;
    private View soundLayout;
    private boolean isOnHover = false;
    private boolean isInside = false;
    private long lashHoverTime = 0;
    private int lastHoverItem = -1;
    private boolean isDown = true;
    private boolean isRun = false;

    private Handler exitHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (watchLayout == null || watchLayout.getVisibility() == View.GONE) {
                return;
            }
            hideAndRemove(watchLayout, (ViewGroup) root);
        }
    };
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (isOnHover) {
                        showTip(lastHoverItem);
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private List<WatchingFocusItem> watchingFocusList;

    public WatchingFocusRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public WatchingFocusRelativeLayout(Context context) {
        this(context, null);
    }

    public void onSeekTouch(MotionEvent event) {
        if (!UIsUtils.isLandscape(getContext()))
            return;
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                isDown = false;
                if (watchLayout != null) {
                    exitHandler.removeMessages(1);
                    exitHandler.sendEmptyMessageDelayed(1, 3000);
                }
                break;
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                isDown = true;
                if (isOnHover && isDown) {
                    /*
                     * 启动判断机制
                     */
                    judgeShowTip();
                }
                break;
        }
    }

    private void judgeShowTip() {
        // if (!isRun) {
        synchronized (this) {
            // if (!isRun) {
            handler.removeMessages(1);
            handler.sendEmptyMessage(1);
            isRun = true;
            // }
        }
        // }

    }

    /**
     * 仅仅凭借该方法判断有一个缺点，当用户手指停留在看点上没有移动时，无法出发看点，需要actionDownOrMove的补充
     * 
     * @param seekBar
     * @param progress
     * @param fromUser
     */
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (!UIsUtils.isLandscape(getContext())/* || !fromUser */) {
            isOnHover = false;
            return;
        }
        int itemTime = onHover(progress);

        // LogInfo.log("lb", "itemTime ="+itemTime+" lastHoverItem="+lastHoverItem+"  isOnHover="+isOnHover);
        if (itemTime != -1) {
            int dotRight = dotList.get(itemTime).getRight();
            int dotLeft = dotList.get(itemTime).getLeft();
            int thumbLeft = fullPlayControllerSeekbar.getThumb().getBounds().left;
            int thumbRight = fullPlayControllerSeekbar.getThumb().getBounds().right;
            LogInfo.log("lb", "dotRight: " + dotRight + "dotLeft: " + dotLeft + "thumbLeft: " + thumbLeft
                    + "thumbRight: " + thumbRight);
            if (thumbRight <= dotLeft || thumbLeft >= dotRight) {
                isInside = false;
                LogInfo.log("lb", "isInside: " + isInside);
            } else {
                isInside = true;
                LogInfo.log("lb", "isInside: " + isInside);
            }
            // /**
            // * 如果已经处于某个看点上方，且上次停留的看点和此次的相同，则不重置时间，同时判断时间是否达到阀值
            // */
            // if(!isOnHover || itemTime != lashHoverTime){
            // lashHoverTime = System.currentTimeMillis();
            // } else if (isOnHover && itemTime == lastHoverItem&&fromUser) {
            // if (System.currentTimeMillis() - lashHoverTime > stayTime) {
            // showTip(itemTime);
            // }
            // } else {
            // lashHoverTime = System.currentTimeMillis();
            // }
            isOnHover = true;
            lastHoverItem = itemTime;
        } else {
            isOnHover = false;
        }
    }

    public void clearFocus() {
        this.removeAllViews();
        watchingFocusList = null;
        watchFocuses.clear();
        dotTimeTree.clear();
        isOnHover = false;
        lashHoverTime = 0;
        lastHoverItem = -1;
    }

    public void drawWatchingFocus(LetvSeekBar fullPlayControllerSeekbar, View root,
            List<WatchingFocusItem> watchingFocusList, ImageView fullPlayControllerPlay, View soundLayout) {
        if (BaseTypeUtils.isListEmpty(watchingFocusList)) {
            setVisibility(GONE);
            return;
        }
        this.setVisibility(View.VISIBLE);
        /**
         * 防止重复绘制
         */
        if (hasDraw(watchingFocusList)) {
            return;
        }
        this.watchingFocusList = watchingFocusList;
        this.fullPlayControllerPlay = fullPlayControllerPlay;
        this.soundLayout = soundLayout;
        clearFocus();
        this.root = root;
        this.fullPlayControllerSeekbar = fullPlayControllerSeekbar;
        LogInfo.log("zhuqiao", "绘制看点");
        for (int i = 0; i < watchingFocusList.size(); i++) {
            WatchingFocusItem watchFocus = watchingFocusList.get(i);
            String timeDot = watchFocus.getTimeDot();
            final int time = StringUtils.stringToLong(timeDot);
            watchFocuses.put(time, watchFocus);
            dotTimeTree.add(time);
            drawWatchFocusDot(time);
        }
        if (this.fullPlayControllerSeekbar instanceof LetvSeekBarFullScreen) {
            ((LetvSeekBarFullScreen) fullPlayControllerSeekbar).setWatchingFocusRelativeLayout(this);
        }

    }

    private boolean hasDraw(List<WatchingFocusItem> watchingFocusList) {
        if (this.watchingFocusList == null || watchingFocusList == null
                || this.watchingFocusList.size() != watchingFocusList.size()) {
            return false;
        }
        for (int i = 0; i < this.watchingFocusList.size(); i++) {
            if (!this.watchingFocusList.get(i).getDesc().equalsIgnoreCase(watchingFocusList.get(i).getDesc())) {
                return false;
            }
        }
        return true;
    }

    @SuppressLint("UseSparseArrays")
    private HashMap<Integer, ImageButton> dotList = new HashMap<Integer, ImageButton>();

    private void drawWatchFocusDot(final int time) {
        final ImageButton dot = new ImageButton(getContext());
        int paddingSize = UIsUtils.dipToPx(mContext,hotSize);
        dot.setPadding(paddingSize, paddingSize, paddingSize, paddingSize);
        dot.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        dot.setBackgroundResource(android.R.color.transparent);
        dot.setImageResource(R.drawable.letv_progresspoint);
        this.addView(dot);
        int[] size = UIsUtils.measure(dot);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) dot.getLayoutParams();
        int left = getLeftMargin(time);
        params.leftMargin = left - size[0] / 2;
        LogInfo.log("zhuqiao", "dot marginLeft:" + params.leftMargin);
        dot.setLayoutParams(params);
        dot.requestLayout();
        dot.setClickable(false);
        dot.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int dotRight = dotList.get(time).getRight();
                int dotLeft = dotList.get(time).getLeft();
                int thumbLeft = fullPlayControllerSeekbar.getThumb().getBounds().left;
                int thumbRight = fullPlayControllerSeekbar.getThumb().getBounds().right;
                isInside = !(thumbRight <= dotLeft || thumbLeft >= dotRight);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        showTip(time);
                        if (mContext instanceof AlbumPlayActivity
                                && ((AlbumPlayActivity) mContext).getFullControllerFragment() != null) {
                            AlbumFullControllerFragment full = ((AlbumPlayActivity) mContext).getFullControllerFragment();
                            if (full.getMeditor() != null) {
                                full.getMeditor().getControllerToVideoListener().onSeekFinish(time);
                            }
                            full.setVisibility(VISIBLE);
                            full.delayHide();
                        } else if(mContext instanceof AlbumPlayRoomActivity
                                && ((AlbumPlayRoomActivity) mContext).getFullControllerFragment() != null) {
                            AlbumRoomFullControllerFragment full = ((AlbumPlayRoomActivity) mContext).getFullControllerFragment();
                            if (full.getMeditor() != null) {
                                full.getMeditor().getControllerToVideoListener().onSeekFinish(time);
                            }
                            full.setVisibility(VISIBLE);
                            full.delayHide();
                        }
                        // 5.7 需求
                        LogInfo.log("zhuqiao", "看点（进度条上）");
                        // 统计
                        StatisticsUtils.staticticsInfoPost(getContext(), "0", "c67", "0012", 6, null,
                                PageIdConstant.fullPlayPage, null, null, null, null, null);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        LogInfo.log("zhuqiao", "dot MotionEvent.ACTION_UP");
                        if (mContext instanceof AlbumPlayActivity
                                && ((AlbumPlayActivity) mContext).getFullControllerFragment() != null) {
                            ((AlbumPlayActivity) mContext).getFullControllerFragment().delayHide();
                        } else if(mContext instanceof AlbumPlayRoomActivity
                                && ((AlbumPlayRoomActivity) mContext).getFullControllerFragment() != null) {
                            ((AlbumPlayRoomActivity) mContext).getFullControllerFragment().delayHide();
                        }
                        if (watchLayout != null) {
                            exitHandler.removeMessages(1);
                            exitHandler.sendEmptyMessageDelayed(1, 5000);
                        }
                        break;
                    default:
                        break;
                }
                if (isInside) {
                    return false;
                } else {
                    return time != onHover(fullPlayControllerSeekbar.getProgress());

                }

            }
        });
        dotList.put(time, dot);
    }

    View watchLayout = null;

    /**
     * 展示看点tip
     * 
     * @param time
     */
    private void showTip(final int time) {
        if (mContext instanceof AlbumPlayActivity && ((AlbumPlayActivity) mContext).getLoadListener() != null
                && ((AlbumPlayActivity) mContext).getLoadListener().isErrorTagShow()) {
            return;
        } else if(mContext instanceof AlbumPlayRoomActivity && ((AlbumPlayRoomActivity) mContext).getLoadListener() != null
                && ((AlbumPlayRoomActivity) mContext).getLoadListener().isErrorTagShow()) {
            return;
        }

        String desc = watchFocuses.get(time).getDesc();
        if (desc.length() > 17) {
            desc = desc.substring(0, 17) + "...";
        }
        if (watchLayout != null) {
            watchLayout.setVisibility(View.GONE);
        }
        final View watchTip = View.inflate(getContext(), R.layout.letv_watchfocus_tip_playerlibs, null);
        //
        View top = watchTip.findViewById(R.id.watchfocus_tip_top);
        View bottom = watchTip.findViewById(R.id.iamgeview_tip);
        watchLayout = watchTip;
        TextView watchFocusTip = (TextView) watchTip.findViewById(R.id.textView_watchFocusTip);
        watchFocusTip.setText(StringUtils.stringForTimeNoHour(time * 1000) + " " + desc);
        watchTip.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                fullPlayControllerSeekbar.setProgress(time);

                if (mContext instanceof AlbumPlayActivity
                        && ((AlbumPlayActivity) mContext).getFullControllerFragment() != null) {
                    AlbumFullControllerFragment full = ((AlbumPlayActivity) mContext).getFullControllerFragment();
                    if (full.getMeditor() != null) {
                        full.getMeditor().getControllerToVideoListener().onSeekFinish(time);
                    }
                    full.setVisibility(VISIBLE);
                    full.delayHide();
                } else if(mContext instanceof AlbumPlayRoomActivity
                        && ((AlbumPlayRoomActivity) mContext).getFullControllerFragment() != null) {
                    AlbumRoomFullControllerFragment full = ((AlbumPlayRoomActivity) mContext).getFullControllerFragment();
                    if (full.getMeditor() != null) {
                        full.getMeditor().getControllerToVideoListener().onSeekFinish(time);
                    }
                    full.setVisibility(VISIBLE);
                    full.delayHide();
                }

                // 5.7需求
                LogInfo.LogStatistics("看点浮层");
                StatisticsUtils.staticticsInfoPost(getContext(), "0", "c676", null, 1, null,
                        PageIdConstant.fullPlayPage, null, null, null, null, null);
            }
        });

        ((ViewGroup) root).addView(watchTip);
        /**
         * 设置位置
         */
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        int[] size = UIsUtils.measure(watchTip);
        int[] locations = new int[2];
        this.getLocationOnScreen(locations);
        LogInfo.log("lb", "left" + time);
        int left = getLeftMargin(time);
        int leftMargin = locations[0] + left - size[0] / 2;
        if (leftMargin < 0) {
            top.setPadding(-leftMargin, 0, 0, 0);
            bottom.setPadding(0, 0, -leftMargin, 0);
        } else if (leftMargin + size[0] > root.getWidth()) {
            top.setPadding(0, 0, root.getWidth() - (leftMargin + size[0]), 0);
            bottom.setPadding((root.getWidth() - (leftMargin + size[0])), 0, 0, 0);
        }
        params.leftMargin = leftMargin;
        params.topMargin = locations[1] + this.getHeight() / 8 - size[1];
        watchTip.setLayoutParams(params);
        watchTip.requestLayout();
    }

    private void hideAndRemove(final View view, final ViewGroup father) {
        AlphaAnimation animationClose = new AlphaAnimation(1f, 0f);
        animationClose.setDuration(500);
        animationClose.setFillAfter(true);
        animationClose.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);
                father.removeView(view);
            }
        });
        view.startAnimation(animationClose);
    }

    /**
     * 判断进度条当前的位置是否在某个热点的热区内
     * 
     * @param progress
     * @return 处于第几个看点的热区内
     */
    private int onHover(int progress) {
        if (fullPlayControllerSeekbar == null) {
            return -1;
        }
        int start = progress - getHotSize();
        start = start < 0 ? 0 : start;
        int end = progress + getHotSize();
        end = end > fullPlayControllerSeekbar.getMax() ? fullPlayControllerSeekbar.getMax() : end;
        for (int i = start; i <= end; i++) {
            if (dotTimeTree.contains(i)) {
                return i;
            }
        }
        return -1;
    }

    private int getHotSize() {
        if (fullPlayControllerSeekbar == null)
            return -1;
        return (int) (((float) hotSize) / getTotalWidth() * fullPlayControllerSeekbar.getMax());
    }

    private int fullPlayControllerPlayW = -1;
    private int soundLayoutW = -1;

    private int getTotalWidth() {
        /**
         * 在没有初始化之前，如果用户点击了seekbar，该方法会被调用，为了防止空指针做如下判断
         */
        if (root == null)
            return 0;
        if (fullPlayControllerPlayW == -1) {
            fullPlayControllerPlayW = UIsUtils.measure(fullPlayControllerPlay)[0];
        }
        if (soundLayoutW == -1) {
            soundLayoutW = UIsUtils.measure(soundLayout)[0];
        }
        return Math.max(UIsUtils.getScreenWidth(mContext), UIsUtils.getScreenHeight(mContext)) - fullPlayControllerPlayW - soundLayoutW - UIsUtils.dipToPx(mContext,29);
    }

    private int getLeftMargin(int time) {
        return (int) (((float) time) / fullPlayControllerSeekbar.getMax() * getTotalWidth()) + UIsUtils.dipToPx(mContext,10);
    }

    public void clearAnimationAndHide() {
        if (watchLayout != null) {
            exitHandler.removeCallbacksAndMessages(null);
            watchLayout.clearAnimation();
            watchLayout.setVisibility(GONE);
        }
    }

}
